package com.raysdata.smartcity.flow.activiti;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.engine.*;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.InputStream;
import java.util.*;

/**
 * Created by zhoukai on 2016/11/17.
 */
public class Test {
    public static void main(String[] args) {
        Test test = new Test();
        //获得流程引擎
        ProcessEngine processEngine = ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault().buildProcessEngine();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        TaskService taskService = processEngine.getTaskService();
        HistoryService historyService = processEngine.getHistoryService();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        IdentityService identityService = processEngine.getIdentityService();

        //identityService.saveUser(User );


        //部署流程定义
//        ProcessDef.deployPD(processEngine,"HR","招聘流程","recruit_process");

        //启动流程实例
//        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("recruit_process");
//        ProcessInstance processInstance = runtimeService.startProcessInstanceById("process:2:11711");
//        Map<String,Object> map =new HashMap<String,Object>();
//        map.put("price","1000000");
//        ProcessInstance processInstance = runtimeService.startProcessInstanceById("process:2:11711","poc_order",map);





        //删除流程定义
//        String pdId = "25001";
//        repositoryService.deleteDeployment(pdId,true);

        //删除流程部署
//        ProcessDef.delProcessDeployById(processEngine,"22501");

        //查询所有流程部署
        List<Deployment> deployments = repositoryService.createDeploymentQuery().list();
        for(Deployment deployment : deployments){
            System.out.println("流程部署信息：" + deployment.toString());
        }

        //查询所有流程定义
//        List<ProcessDefinition> pds = repositoryService.createProcessDefinitionQuery().processDefinitionKey("recruit_process").list();
//        for(ProcessDefinition pd : pds){
//            System.out.println("流程定义信息：" + pd.toString());
//        }

        //删除流程实例
//        runtimeService.deleteProcessInstance("15001","");

        //查询流程实例
        List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().list();
        for(ProcessInstance pi : processInstances){
            System.out.println("流程实例信息：" + pi.toString());
        }
        //获得当前任务
//        List<Task> tasks = taskService.createTaskQuery().processInstanceId("30001").list();
//        for(Task task : tasks){
//            System.out.println("task------");
//            System.out.println(task.toString());
//        }

        //根据当前登录人查询我的待签收任务
        String currentLoginUser = "tech3";
//        List<Task> myTasks = taskService.createTaskQuery().taskCandidateOrAssigned(currentLoginUser).list();
//        for(Task t : myTasks){
//            System.out.println(t.toString());
//            String taskAssigneeInfo = t.getAssignee();
//            if(StringUtils.isEmpty(taskAssigneeInfo)){
//                //待签收状态
//                System.out.println("待签收");
//            }else{
//                //已签收状态（待办状态）
//                System.out.println("已签收");
//            }
//        }

        //当前登录人签收任务
        String taskId = "47502";
//        taskService.claim(taskId,currentLoginUser);


        //根据当前登录人查询待办任务（已签收任务）
//        List<Task> myTask2 = taskService.createTaskQuery().taskAssignee(currentLoginUser).list();
//        for(Task t : myTask2){
//            System.out.println(currentLoginUser + "的已签收【待办】任务：" + t.toString());
//
//        }

        //当前登录人完成任务
//       taskService.complete(taskId);


        //查看流程实例结束信息
//        HistoricProcessInstance historicProcessInstance =
//                historyService.createHistoricProcessInstanceQuery().processInstanceId("42501").singleResult();
//        System.out.println("Process instance end time: " + historicProcessInstance.getEndTime());
//        System.out.println("Process instance 用时: " + historicProcessInstance.getDurationInMillis()/1000/60 + "分钟");

        //查看流程流转历史
//        List<HistoricTaskInstance> tis = historyService.createHistoricTaskInstanceQuery().processInstanceId("42501")
//                .finished()
//                .orderByHistoricTaskInstanceEndTime().asc().list();
//        for(HistoricTaskInstance ti : tis){
//            System.out.println(ti.toString() + ":" + ti.getAssignee() + " at: " + ti.getEndTime() + " 用时：" + ti.getDurationInMillis()/1000/60+"分钟");
//        }

        //根据组获得所有用户，并显示每个用户的待签收任务
//        List<User> users = identityService.createUserQuery().memberOfGroup("tech").list();
//        for(User u : users){
//            List<Task> myTasks2 = taskService.createTaskQuery().taskCandidateOrAssigned(u.getId()).list();
//            for(Task t : myTasks2){
//                System.out.println(u.getId() + "的待签收任务：" + t.toString());
//            }
//        }

        //下一任务
//        TaskDefinition taskDefinition = test.nextTaskDefinition(runtimeService,repositoryService,historyService,"22505");
//        System.out.println(taskDefinition.getNameExpression().getExpressionText() + ":" + taskDefinition.getCandidateGroupIdExpressions().toString());

//        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("hr").list();
//        for (Task task : tasks) {
//            System.out.println("人力资源部的任务：name:"+task.getName()+",id:"+task.getId());
////            taskService.claim(task.getId(), "hr2");
//        }


        //获得所有组
//        IdentityService identityService = processEngine.getIdentityService();
//        List<Group> groups = identityService.createGroupQuery().list();
//        for(Group group : groups){
//            System.out.println(group.getName() + ":" + group.getType());
//        }
        processEngine.close();
    }


    public void viewImage(ProcessEngine processEngine) throws Exception {
        // 创建仓库服务对对象
        RepositoryService repositoryService = processEngine.getRepositoryService();
        // 从仓库中找需要展示的文件
        String deploymentId = "701";
        List<String> names = repositoryService.getDeploymentResourceNames(deploymentId);
        String imageName = null;
        for (String name : names) {
            if (name.indexOf(".png") >= 0) {
                imageName = name;
            }
        }
        if (imageName != null) {
//     System.out.println(imageName);
            File f = new File("e:/" + imageName);
            // 通过部署ID和文件名称得到文件的输入流
            InputStream in = repositoryService.getResourceAsStream(deploymentId, imageName);
            //FileUtils.copyInputStreamToFile(in, f);
        }

    }


    /**
     * 流程跟踪图
     * @return
     */
    public String traceProcess(RuntimeService runtimeService, RepositoryService repositoryService, String processInstanceId) {
        try {
            Execution execution = runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult();//执行实例
            Object property = PropertyUtils.getProperty(execution, "activityId");
            String activityId = "";
            if (property != null) {
                activityId = property.toString();
            }
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                    .getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
            List<ActivityImpl> activitiList = processDefinition.getActivities();//获得当前任务的所有节点
            ActivityImpl activity = null;
            for (ActivityImpl activityImpl : activitiList) {
                String id = activityImpl.getId();
                if (id.equals(activityId)) {//获得执行到那个节点
                    activity = activityImpl;
                    break;
                }
            }
            Map<String, Object> activityImageInfo = new HashMap<String, Object>();
            activityImageInfo.put("x", activity.getX());
            activityImageInfo.put("y", activity.getY());
            activityImageInfo.put("width", activity.getWidth());
            activityImageInfo.put("height", activity.getHeight());

            //Struts2Utils.renderJson(activityImageInfo);
        } catch (Exception e) {
           // logger.error("查看流程跟踪图出错：");
        }
        return null;
    }
}
